package com.jinke.tank;

import com.jinke.game.GameFrame;
import com.jinke.util.Myutils;
import com.jinke.util.TankPool;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class EnemyTank extends Tank{
    private long lastActionTime = 0;
    private static final Image[] enemyImg;

    static {
        enemyImg = new Image[4];
        try {
            enemyImg[0] = ImageIO.read(Objects.requireNonNull(com.jinke.tank.EnemyTank.class.getResourceAsStream("/img/ul.png")));
            enemyImg[1] = ImageIO.read(Objects.requireNonNull(com.jinke.tank.EnemyTank.class.getResourceAsStream("/img/dl.png")));
            enemyImg[2] = ImageIO.read(Objects.requireNonNull(com.jinke.tank.EnemyTank.class.getResourceAsStream("/img/ll.png")));
            enemyImg[3] = ImageIO.read(Objects.requireNonNull(com.jinke.tank.EnemyTank.class.getResourceAsStream("/img/rl.png")));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public EnemyTank(int x, int y, int dir) {
        super(x, y, dir);
    }


    @Override
    public boolean isPlayerTank() {
        return false; // 敌方坦克返回 false
    }



    public EnemyTank(int x, int y, int dir, int boundWidth, int boundHeight) {
        super(x, y, dir, boundWidth, boundHeight);
    }

    public static Tank createEnemyTank() {
        int x = Myutils.getRandom(0, 1) == 0 ? RADIUS : GameFrame.gamePanel.getWidth()-RADIUS;
        int dir = Myutils.getRandom(0, 2);
        int y = RADIUS;
//        Tank enemy = new EnemyTank(x, y, dir);
        Tank enemy = TankPool.instance.getEnemyObj(x, y, dir);
        enemy.state = STATE_MOVE;
        return enemy;
    }

    @Override
    public void logic() {
        // AI逻辑
        long currentTime = System.currentTimeMillis();

        // 自动移动逻辑保持不变
        switch (state){
            case STATE_NORMAL:
                break;
            case STATE_MOVE:
                move();
                break;
            case STATE_DEAD:
                die(this);
                break;
        }

        // AI决策逻辑
        if (currentTime - lastActionTime > 100) { // 每0.1秒做一次决策
            // 随机改变方向
            if (Math.random() < 0.3) {
                dir = (int)(Math.random() * 4);
            }

            // 随机开火
            if (Math.random() < 0.1) {
                fire(this);
            }

            lastActionTime = currentTime;
        }
    }

    @Override
    public void drawImgTank(Graphics g) {
        g.drawImage(enemyImg[dir], x-RADIUS, y-RADIUS, null);
    }

    public void reset(int x, int y, int dir) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.name = Myutils.getRandomName();
    }
}
